package il.ac.tau.cvws.scrabblesidekick.server.servlet;

import il.ac.tau.cvws.scrabblesidekick.server.app.manager.GameManager;
import il.ac.tau.cvws.scrabblesidekick.server.util.debug.DebugUtil;
import il.ac.tau.cvws.scrabblesidekick.server.util.debug.DebugUtil.DebugTypes;
import il.ac.tau.cvws.scrabblesidekick.server.util.exception.ExceptionConstant;
import il.ac.tau.cvws.scrabblesidekick.server.util.exception.ScrabbleSidekickException;
import il.ac.tau.cvws.scrabblesidekick.server.util.file.ConversionUtil;
import il.ac.tau.cvws.scrabblesidekick.shared.comm.request.FindWordRequestData;
import il.ac.tau.cvws.scrabblesidekick.shared.comm.response.ExceptionResponsePayload;
import il.ac.tau.cvws.scrabblesidekick.shared.comm.response.FindWordResponsePayload;
import il.ac.tau.cvws.scrabblesidekick.shared.comm.response.ResponsePayload;
import il.ac.tau.cvws.scrabblesidekick.shared.datatype.WordPlacement;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.googlecode.javacv.cpp.opencv_core.IplImage;

@WebServlet("/GameServlet")
@MultipartConfig
public class GameServlet extends ScrabbleSidekickServlet 
{
	private static final long serialVersionUID = 1L;

    public GameServlet() 
    {
        super();
    }

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException 
	{
		doPost(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{
		ResponsePayload responsePayload = null;		

		try
		{
			FindWordRequestData data = (FindWordRequestData)getRequestPayload(request);
			
			DebugUtil.saveImage(IplImage.createFrom(ConversionUtil.convertStringToImage(data.getBoardImage().getImage())), 
					DebugTypes.GAME_SERVLET,
					"incoming_img", 
					true);
	
			WordPlacement word = GameManager.instance().solveGame(data.getBoardImage(), data.getRack(),
					data.getScreenWidth(), data.getScreenHeight(),
					data.getStorageKey(), 1);
			
			if (word != null)
			{
				responsePayload = new FindWordResponsePayload(word);
			}
			else
			{
				responsePayload = new ExceptionResponsePayload(ExceptionConstant.SOLVER_HAS_FAILED);
			}
		}
		catch (ScrabbleSidekickException e)
		{
			responsePayload = new ExceptionResponsePayload(e.getMSG());
		}
		
		sendResponsePayload(response, responsePayload);
	}
}
